import {
  getDetails
} from "api/api"

export default {
  state: {
    details:{}
  },
  getters: {
    categoryView(state){
      return state.details.categoryView ? state.details.categoryView : {}
    },
    skuInfo(state){
      return state.details.skuInfo ? state.details.skuInfo : []
    },
    spuSaleAttrList(state){
      return state.details.spuSaleAttrList ? state.details.spuSaleAttrList : []
    },
    selectValInfo(state,getters){
      let arr = []
      getters.spuSaleAttrList.forEach(attr=>{
        attr.spuSaleAttrValueList.forEach(val=>{
          if(val.isChecked==='1'){
            arr.push({
              ...val,
              attrId:attr.id
            })
          }
        })
      })
      return arr
    }
  },
  mutations: {
    getDetails(state, details) {
      state.details = details
    },
    updateIsChecked(state,{attrId,valId}){
      // 循环，找到对应的属性值，先排他
      state.details.spuSaleAttrList.forEach(attr=>{
        if(attr.id===attrId){
          attr.spuSaleAttrValueList.forEach(val=>{
            val.isChecked = '0'
            if(val.id===valId){
              val.isChecked = '1'
            }
          })
        }
      })
    }
  },
  actions: {
    async getDetails(store, id) {
      try {
        const {data,code} = await getDetails(id)
        if (code === 200) {
          store.commit("getDetails",data)
        }
        return {data,code}
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}
